/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.meteocal.sessionbeans;

import it.polimi.meteocal.entities.Event;
import it.polimi.meteocal.entities.Group;
import it.polimi.meteocal.entities.Invitation;
import it.polimi.meteocal.entities.User;
import java.security.Principal;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


@Stateless
public class UserManager {

    @PersistenceContext
    EntityManager em;
    
    @Inject
    Principal principal;

    public int save(User user) {
        /* A questo punto, sono settati Username, Email e Password. Aggiungo il
           controllo sull'unicità di Username e Email. */
        Query q1 = em.createQuery("SELECT u FROM User u WHERE u.username = :username");
        q1.setParameter("username", user.getUsername());
        if(!q1.getResultList().isEmpty()){
            return -1;
        }
        Query q2 = em.createQuery("SELECT u FROM User u WHERE u.email = :email");
        q2.setParameter("email", user.getEmail());
        if(!q2.getResultList().isEmpty()){
            return -1;
        }       
        user.setCalendarVisibility("public");
        user.setGroupName(Group.USERS);    
        em.persist(user);
        return 0;
    }
    
    public void saveModifiedUser(User u){
        em.merge(u);
    }

    public void unregister() {
        em.remove(getLoggedUser());
    }

    public User getLoggedUser() {
        Query q = em.createQuery("SELECT u.idu FROM User u WHERE u.email = :email");
        q.setParameter("email", principal.getName()); /* principal.getName() ritorna l'EMAIL dell'user loggato */
        Integer IDU = (Integer) q.getSingleResult();
        /* In find() il secondo parametro è necessariamente la PK. Nel nostro
           caso quindi è l'ID NUMERICO dell'utente. */
        User user = em.find(User.class, IDU);
        em.refresh(user);
        return user;       
    }

    public List<User> readAllUsersFromDB() {
        List<User> results = em.createNamedQuery("User.findAll").getResultList();
        return results;
    }
    
    public void refreshUser(User u){
        em.refresh(em.merge(u));
    }
    
    public void setParticipation(Event e, boolean b){
        User logged = this.getLoggedUser();
        for(Invitation i : logged.getInvitationList()){
            if(i.getEvent().equals(e)){
                i.setParticipant(b);
                i.setAcceptDate(new Date());
                em.merge(i);
                break;
            }
        }
    }
    
}
